package com.asm.blog.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.asm.blog.common.dto.LoginDto;
import com.asm.blog.common.lang.Result;
import com.asm.blog.entity.User;
import com.asm.blog.service.UserService;
import com.asm.blog.util.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录 退出 接口
 */
@RestController
public class AccountController {

    // 注入 用户服务层 用来查询用户
    @Autowired
    UserService userService;

    // 注入 jwt 工具
    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(
            @Validated @RequestBody LoginDto loginDto,
            HttpServletResponse response)
    {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));

        // 这个方法 断定错误则抛出 IllegalArgumentException ，所以在全局异常处理 也要 定义此异常处理
        Assert.notNull(user, "用户不存在");

        if(!user.getPassword().equals(   SecureUtil.md5(loginDto.getPassword())   ))
        {
            return Result.fail("密码错误");
        }else if(user.getStatus() != 1)
        {
            return Result.fail("账户被锁定了");
        }

        // 生成 jwt返回
        String jwt = jwtUtils.generateToken(user.getId());

        // 一般是 放在 header 里面
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-headers", "Authorization");


        Map<Object, Object> map = MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map();

        return Result.succ(map);
    }

    @RequiresAuthentication  // 需要登录才能推出
    @GetMapping("/logout")
    public Result logout()
    {
        SecurityUtils.getSubject().logout();

        return Result.succ(null);
    }






}
